package com.zzl.admin.controller.sso;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.oltu.oauth2.client.OAuthClient;
import org.apache.oltu.oauth2.client.URLConnectionClient;
import org.apache.oltu.oauth2.client.request.OAuthBearerClientRequest;
import org.apache.oltu.oauth2.client.request.OAuthClientRequest;
import org.apache.oltu.oauth2.client.response.OAuthAccessTokenResponse;
import org.apache.oltu.oauth2.client.response.OAuthResourceResponse;
import org.apache.oltu.oauth2.common.OAuth;
import org.apache.oltu.oauth2.common.exception.OAuthProblemException;
import org.apache.oltu.oauth2.common.exception.OAuthSystemException;
import org.apache.oltu.oauth2.common.message.types.GrantType;
import org.jasig.cas.client.util.XmlUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * description: 基于oauth2单点登录
 * @author zzl
 * @date 2022-08-24 09:06:31
 */
@RestController
public class SsoDemoController {

    private String tokenUrl = "";
    private String client_id = "";
    private String callBackURL = "";
    private String accessTokenUrl = "";
    private String client_secret = "";
    private String profile = "";

    @GetMapping(value="/mainPage")
    public Object mainPage(HttpServletRequest request, HttpServletResponse response) throws OAuthSystemException, OAuthProblemException, Exception {
        //判断是否有授权码
        String code = request.getParameter("code");
        //判断是否有logoutRequest传参，有该参数代表需要退出并清除session
        String logoutRequest = request.getParameter("logoutRequest");
        if(logoutRequest != null && logoutRequest.length()> 0){
            // 获取登陆验证时的授权码
            String token = XmlUtils.getTextForElement(logoutRequest, "SessionIndex");
            //清除session

            return null;
        }
        if(request.getSession().getAttribute("usercode")==null){
            String url = tokenUrl + "?client_id=" + client_id + "&redirect_uri="+callBackURL+"&response_type=code&state=123";
            if(StringUtils.isEmpty(code)) {
                //到统一认证请求获取授权码
                response.sendRedirect(url);
                return null;
            }else {
                OAuthClientRequest req = OAuthClientRequest
                        .tokenLocation(accessTokenUrl)
                        .setClientId(client_id)
                        .setClientSecret(client_secret)
                        .setGrantType(GrantType.AUTHORIZATION_CODE)
                        .setRedirectURI(callBackURL)
                        .setCode(code)
                        .buildBodyMessage();

                OAuthClient oAuthClient = new OAuthClient(new URLConnectionClient());
                //通过oauthorizeCode去获取access_token
                OAuthAccessTokenResponse oauthResponse = oAuthClient.accessToken(req);

                System.out.println("Access Token: " + oauthResponse.getAccessToken());
                System.out.println("Expires In: " + oauthResponse.getExpiresIn());
                //String serviceApi=profile+"?access_token="+oauthResponse.getAccessToken();
                OAuthClientRequest bearerClientRequest = new OAuthBearerClientRequest(profile)
                        .setAccessToken(oauthResponse.getAccessToken())
                        .buildQueryMessage();
                //通过access_token获取userInfo
                OAuthResourceResponse resourceResponse = oAuthClient.resource(bearerClientRequest, OAuth.HttpMethod.GET,OAuthResourceResponse.class);
                String resBody = resourceResponse.getBody();
                System.out.println(resBody);
                JSONObject json = JSONObject.parseObject(resBody);
                request.getSession().setAttribute("status", json.get("status"));
                request.getSession().setAttribute("usercode", json.get("userCode"));
                System.out.println(request.getSession().getAttribute("usercode"));
            }
        }
        ModelAndView mv = new ModelAndView("mainPage/index");
        return mv;
    }

}
